package com.uwo.house.service.serviceImpl;

import com.uwo.house.beans.Member;
import com.uwo.house.beans.User;
import com.uwo.house.beans.UserRole;
import com.uwo.house.beans.request.AddStaffReq;
import com.uwo.house.beans.request.ClientModifyReq;
import com.uwo.house.beans.request.ModifyStaffReq;
import com.uwo.house.beans.response.StaffUserResp;
import com.uwo.house.beans.response.UserResp;
import com.uwo.house.dao.MemberMapper;
import com.uwo.house.dao.UserMapper;
import com.uwo.house.dao.UserRoleMapper;
import com.uwo.house.kits.EncryptKits;
import com.uwo.house.kits.MatcherKit;
import com.uwo.house.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by yanhao on 2017/6/16.
 */
@Service
public class UserService implements IUserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    UserRoleMapper userRoleMapper;


    public User selectByUsername(String username){
        // 验证用户是否存在
        User user = null;

        if(MatcherKit.isEmail(username))
            user = userMapper.selectByEmail(username);
        else if(MatcherKit.isMobile(username))
            user = userMapper.selectByMobile(username);
        else
            user = userMapper.selectByUsername(username);
        return user;
    }

    public User selectByUnionid(String unionid){
        // 验证用户是否存在
        User user =  userMapper.selectByUsername(unionid);
        return user;
    }

    public Member selectById(String mid) {
        return null;
    }

    @Transactional
    public boolean register(String mobile, String password) {
        String mid = UUID.randomUUID().toString().replaceAll("-","");
        Member member = new Member();
        member.setId(mid);
        member.setCreatedTime(new Date());
        member.setUpdatedTime(new Date());
        memberMapper.save(member);

        User user = new User();
        user.setId(UUID.randomUUID().toString().replaceAll("-",""));
        user.setMobile(mobile);
        user.setMember(member);
        user.setSalt(EncryptKits.generatePassword());
        user.setUsername(mobile);
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String(password)).toLowerCase() + user.getSalt()).toLowerCase();
        user.setPassword(pwd);
        user.setStatus(1);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        user.setAccountType("1");//手机号码注册
        userMapper.save(user);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(2L);
        int count = userRoleMapper.save(userRole);

        return (count > 0);
    }

    @Transactional
    public void autoRegister(String unionid, String accountType, Member member) {
        String mid = UUID.randomUUID().toString().replaceAll("-","");
        member.setId(mid);
        member.setCreatedTime(new Date());
        member.setUpdatedTime(new Date());
        memberMapper.save(member);

        User user = new User();
        user.setId(UUID.randomUUID().toString().replaceAll("-",""));
        user.setAccountType(accountType);
        user.setMember(member);
        user.setSalt(EncryptKits.generatePassword());
        user.setUsername(unionid);
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String("123456")).toLowerCase() + user.getSalt()).toLowerCase();
        user.setPassword(pwd);
        user.setStatus(1);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        userMapper.save(user);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(2L);
        userRoleMapper.save(userRole);
    }

    public boolean validatePwd(User user, String password, String oldPassword){
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String(password)).toLowerCase() + user.getSalt()).toLowerCase();
        String oldPwd = EncryptKits.Md5(EncryptKits.Md5(new String(oldPassword)).toLowerCase() + user.getSalt()).toLowerCase();
        if(!user.getPassword().equalsIgnoreCase(oldPwd))
            return false;
        if(pwd.equalsIgnoreCase(oldPwd))
            return false;
        user.setPassword(pwd);
        int count = userMapper.modify(user);
        return (count > 0);
    }

    public boolean modifyMobile(User user, String mobile) {
        //User user = userMapper.selectByMid(user.get);
        user.setMobile(mobile);
        int count = userMapper.modify(user);
        return (count > 0);
    }

    public boolean modifyPassword(User user, String password) {
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String(password)).toLowerCase() + user.getSalt()).toLowerCase();
        user.setPassword(pwd);
        int count = userMapper.modify(user);
        return (count > 0);
    }

    public int modifyStaffPassword(User user, String password) {
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String(password)).toLowerCase() + user.getSalt()).toLowerCase();
        user.setPassword(pwd);
        return userMapper.modifyStaffPassword(user);
    }

    public List<UserResp> getUsers(String userName, Date dateFrom, Date dateTo){
        return userMapper.getUsers(userName,dateFrom,dateTo);
    }

    public int deleteUser(String id) {
        return userMapper.deleteUser(id);
    }

    public List<StaffUserResp> getStaffList(int roleId, String userName, String name, String address,String supplyClass) {
        return userMapper.getStaffList(roleId, userName, name, address,supplyClass);
    }

    public int modifyStaffUser(ModifyStaffReq modifyStaffReq){
        return  userMapper.modifyStaffUser(modifyStaffReq);
    }

    @Transactional
    public int addStaffUser(AddStaffReq addStaffReq) {
        int result1 = userMapper.addStaffUser(addStaffReq);
        int result2 = userMapper.addRole(addStaffReq.getId(), addStaffReq.getRoleId());
        if (result1 == 1 && result2 == 1) {
            return 1;
        }
        return 0;
    }

    public User getUserByMobile(String mobile){
        return userMapper.getUserByMobile(mobile);
    }

    public UserResp getUserByUserName(String username){
        return userMapper.getUserByUserName(username);
    }

    public  String getRoleIdByUserId(String userId){
        return userMapper.getRoleIdByUserId(userId);
    }

    public int checkMobile(String checkMobile){
        return userMapper.checkMobile(checkMobile);
    }

    public String getNameByUserId(String userId){
        return userMapper.getNameByUserId(userId);
    }

    public StaffUserResp getStaffUserInfo(String userId){
        return userMapper.getStaffUserInfo(userId);
    }

    public User selectUserById(String userId) {
        return userMapper.selectById(userId);
    }

    public int modifyClientInfo(ClientModifyReq clientModifyReq){
        return userMapper.modifyClientInfo(clientModifyReq);
    }

    public int modifyAliAccount(String aliAccount, String userId){
        return userMapper.modifyAliAccount(aliAccount,userId);
    }
}
